package com.controller;

import com.domain.Book;
import com.domain.Result;
import com.service.BookService;
import com.statics.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result add(@RequestBody Book book) {
        boolean flag = bookService.add(book);
        System.out.println(flag);

        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable int id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        System.out.println(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable int id) {

        Book book = bookService.getById(id);
        System.out.println(book);
        String s = book != null ? "" : "查询失败请重新查询";
        Integer code = book != null ? Code.SELECT_OK : Code.SELECT_ERR;

        return new Result(code,book,s);
    }

    @GetMapping
    public Result getAll() {
        List<Book> books = bookService.getAll();
        System.out.println(books);
        String s = books != null ? "" : "查询失败请重新查询";
        Integer code = books != null ? Code.SELECT_OK : Code.SELECT_ERR;

        return new Result(code,books,s);
    }

}
